<template>
  <view class="todo-edit">
    <u-form :model="formData" ref="uForm" :rules="rules">
      <u-form-item label="标题" prop="title" required>
        <u-input v-model="formData.title" placeholder="请输入标题" />
      </u-form-item>
      
      <u-form-item label="内容" prop="content">
        <u-textarea v-model="formData.content" placeholder="请输入内容描述" height="200" />
      </u-form-item>
      
      <u-form-item label="优先级" prop="priority">
        <u-radio-group v-model="formData.priority">
          <u-radio :name="0" label="普通"></u-radio>
          <u-radio :name="1" label="重要"></u-radio>
          <u-radio :name="2" label="紧急"></u-radio>
        </u-radio-group>
      </u-form-item>
      
      <u-form-item label="状态" prop="status">
        <u-radio-group v-model="formData.status">
          <u-radio :name="0" label="待办"></u-radio>
          <u-radio :name="1" label="进行中"></u-radio>
          <u-radio :name="2" label="已完成"></u-radio>
          <u-radio :name="3" label="已取消"></u-radio>
        </u-radio-group>
      </u-form-item>
      
      <u-form-item label="截止时间" prop="deadline">
        <view class="time-input-container">
          <view class="picker-wrapper" @click="openDeadlinePicker">
            <u-input
              v-model="deadlineText"
              disabled
              placeholder="请选择截止时间"
            />
          </view>
          <u-icon 
            v-if="deadlineText" 
            name="close" 
            size="28" 
            @click="clearDeadline"
            class="clear-icon"
          ></u-icon>
        </view>
        <u-datetime-picker
          v-model="formData.deadline"
          :show="showDeadlinePicker"
          mode="datetime"
          @confirm="onDeadlineConfirm"
          @cancel="showDeadlinePicker = false"
        ></u-datetime-picker>
      </u-form-item>
      
      <u-form-item label="提醒时间" prop="remindTime">
        <view class="time-input-container">
          <view class="picker-wrapper" @click="openRemindTimePicker">
            <u-input
              v-model="remindTimeText"
              disabled
              placeholder="请选择提醒时间"
            />
          </view>
          <u-icon 
            v-if="remindTimeText" 
            name="close" 
            size="28" 
            @click="clearRemindTime"
            class="clear-icon"
          ></u-icon>
        </view>
        <u-datetime-picker
          v-model="formData.remindTime"
          :show="showRemindTimePicker"
          mode="datetime"
          @confirm="onRemindTimeConfirm"
          @cancel="showRemindTimePicker = false"
        ></u-datetime-picker>
      </u-form-item>
    </u-form>
    
    <view class="form-actions">
      <u-button type="primary" @click="submitForm" :loading="submitting">保存</u-button>
      <u-button @click="cancelEdit">取消</u-button>
    </view>
  </view>
</template>

<script>
import { getTodoById, createTodo, updateTodo } from '@/api/todo'
import { formatDate, formatDateForBackend } from '@/utils/date'

export default {
  data() {
    return {
      todoId: null,
      isEdit: false,
      submitting: false,
      showDeadlinePicker: false,
      showRemindTimePicker: false,
      deadlineText: '',
      remindTimeText: '',
      formData: {
        title: '',
        content: '',
        priority: 0,
        status: 0,
        deadline: '',
        remindTime: ''
      },
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ]
      }
    }
  },
  onLoad(options) {
    console.log('页面加载参数:', options)
    if (options.id) {
      this.todoId = options.id
      this.isEdit = true
      this.loadTodoDetail()
    } else {
      console.log('新增模式初始化')
      // 新增模式下，初始化表单默认值
      this.formData = {
        title: '',
        content: '',
        priority: 0,
        status: 0,
        deadline: '',
        remindTime: ''
      }
    }
  },
  methods: {
    formatDate,
    async loadTodoDetail() {
      try {
        console.log('加载待办详情, ID:', this.todoId)
        const res = await getTodoById(this.todoId)
        console.log('获取到待办详情:', res)
        
        this.formData = {
          title: res.title,
          content: res.content || '',
          priority: res.priority || 0,
          status: res.status || 0,
          deadline: res.deadline ? new Date(res.deadline) : '',
          remindTime: res.remindTime ? new Date(res.remindTime) : ''
        }
        
        if (res.deadline) {
          this.deadlineText = this.formatDate(res.deadline, 'YYYY-MM-DD HH:mm')
        }
        
        if (res.remindTime) {
          this.remindTimeText = this.formatDate(res.remindTime, 'YYYY-MM-DD HH:mm')
        }
      } catch (error) {
        console.error('获取待办事项详情失败', error)
        uni.showToast({
          title: '获取详情失败',
          icon: 'none'
        })
      }
    },
    openDeadlinePicker() {
      // 如果没有设置截止时间，则默认设置为当前时间
      if (!this.formData.deadline) {
        this.formData.deadline = new Date()
      }
      this.showDeadlinePicker = true
    },
    openRemindTimePicker() {
      // 如果没有设置提醒时间，则默认设置为当前时间
      if (!this.formData.remindTime) {
        this.formData.remindTime = new Date()
      }
      this.showRemindTimePicker = true
    },
    onDeadlineConfirm(e) {
      this.formData.deadline = e.value
      this.deadlineText = this.formatDate(e.value, 'YYYY-MM-DD HH:mm')
      this.showDeadlinePicker = false
    },
    onRemindTimeConfirm(e) {
      this.formData.remindTime = e.value
      this.remindTimeText = this.formatDate(e.value, 'YYYY-MM-DD HH:mm')
      this.showRemindTimePicker = false
    },
    clearDeadline() {
      this.formData.deadline = ''
      this.deadlineText = ''
      uni.showToast({
        title: '已清除截止时间',
        icon: 'none'
      })
    },
    clearRemindTime() {
      this.formData.remindTime = ''
      this.remindTimeText = ''
      uni.showToast({
        title: '已清除提醒时间',
        icon: 'none'
      })
    },
    submitForm() {
      console.log('提交表单，开始验证')
      
      // 简单验证：标题必填
      if (!this.formData.title || this.formData.title.trim() === '') {
        uni.showToast({
          title: '请输入标题',
          icon: 'none'
        })
        return
      }
      
      console.log('验证通过，开始保存数据')
      this.saveData()
    },
    async saveData() {
      try {
        console.log('开始保存数据')
        this.submitting = true
        
        // 创建数据副本，避免直接修改表单数据
        const data = {
          ...this.formData
        }
        
        // 转换日期格式，使用统一的日期格式化函数
        // 处理deadline，无论是Date对象、时间戳还是ISO字符串
        if (data.deadline) {
          data.deadline = formatDateForBackend(data.deadline);
          console.log('格式化后的deadline:', data.deadline);
        }
        
        // 处理remindTime，无论是Date对象、时间戳还是ISO字符串
        if (data.remindTime) {
          data.remindTime = formatDateForBackend(data.remindTime);
          console.log('格式化后的remindTime:', data.remindTime);
        }
        
        console.log('准备保存的数据:', data)
        
        let result = null
        
        if (this.isEdit) {
          // 更新
          console.log('更新待办, ID:', this.todoId)
          result = await updateTodo(this.todoId, data)
          console.log('更新结果:', result)
          uni.showToast({
            title: '更新成功',
            icon: 'success'
          })
        } else {
          // 创建
          console.log('创建新待办')
          result = await createTodo(data)
          console.log('创建结果:', result)
          uni.showToast({
            title: '创建成功',
            icon: 'success'
          })
        }
        
        // 返回上一页
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      } catch (error) {
        console.error('保存失败', error)
        uni.showToast({
          title: '保存失败: ' + (error.message || '未知错误'),
          icon: 'none'
        })
      } finally {
        this.submitting = false
      }
    },
    cancelEdit() {
      uni.navigateBack()
    }
  }
}
</script>

<style lang="scss" scoped>
.todo-edit {
  padding: 30rpx;
  
  .time-input-container {
    position: relative;
    display: flex;
    align-items: center;
    
    .picker-wrapper {
      flex: 1;
    }
    
    .u-input {
      width: 100%;
    }
    
    .clear-icon {
      position: absolute;
      right: 20rpx;
      color: #999;
      z-index: 10;
    }
  }
  
  .form-actions {
    margin-top: 60rpx;
    display: flex;
    justify-content: space-between;
    
    .u-button {
      flex: 1;
      margin: 0 20rpx;
      
      &:first-child {
        margin-left: 0;
      }
      
      &:last-child {
        margin-right: 0;
      }
    }
  }
}
</style> 